package com.example.exam.controller.fileController;

import com.example.exam.utils.AmazeS3Utils;
import lombok.SneakyThrows;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * 加载试题图片
 *
 * @author zhang
 */
@RestController
@RequestMapping("/img")
@ApiIgnore
public class QuestionImgController {
    private final AmazeS3Utils amazeS3Utils;

    public QuestionImgController(AmazeS3Utils amazeS3Utils) {
        this.amazeS3Utils = amazeS3Utils;
    }

    @SneakyThrows
    @GetMapping("/{img}")
    public ResponseEntity<byte[]> questionImg(@PathVariable String img) {
        InputStream inputStream = amazeS3Utils.download(img);
        if (inputStream == null) {
            return ResponseEntity.notFound().build();
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int read;
        byte[] data = new byte[1024];
        while ((read = inputStream.read(data, 0, data.length)) != -1) {
            outputStream.write(data, 0, read);
        }
        outputStream.flush();
        return ResponseEntity.ok(outputStream.toByteArray());
    }
}
